package org.wenhua.yuan.and.module_flutter.flutterM1.fragment

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import io.flutter.embedding.android.FlutterTextureView
import io.flutter.embedding.android.FlutterView
import io.flutter.embedding.engine.FlutterEngine
import org.wenhua.yuan.R
import org.wenhua.yuan.and.fragment.IBaseFragment
import org.wenhua.yuan.and.module_flutter.flutterM1.bridge.JFlutterCacheManager
import org.wenhua.yuan.and.util.ContextGlobal

abstract class BaseFlutterFragment(moduleName:String): IBaseFragment(){

    private var flutterView:FlutterView? = null
    private var cached:Boolean = JFlutterCacheManager.instance!!.hasCached(moduleName)
    private var flutterEngine:FlutterEngine? = null
    init {
        flutterEngine = JFlutterCacheManager.instance!!.getFlutterEngineCached(moduleName, ContextGlobal.get())
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        // 注册flutter/platform_views 插件以便能够处理native view
        if (!cached) {
            flutterEngine!!.platformViewsController!!.attach(
                activity,
                flutterEngine!!.renderer,
                flutterEngine!!.dartExecutor
            )
        }
    }

    override fun getLayoutRes(): Int {
        return R.layout.layout_flutter_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (rootLayout as ViewGroup).addView(createFlutterView(activity!!))
    }

    private fun createFlutterView(activity: FragmentActivity): View? {
        val flutterTextureView = FlutterTextureView(activity)
        flutterView = FlutterView(activity, flutterTextureView)
        return flutterView
    }

    override fun onStart() {
        flutterView!!.attachToFlutterEngine(flutterEngine!!)
        super.onStart()
    }

    override fun onResume() {
        super.onResume()
        flutterEngine!!.lifecycleChannel.appIsResumed()
    }

    override fun onPause() {
        super.onPause()
        flutterEngine!!.lifecycleChannel.appIsInactive()
    }

    override fun onStop() {
        super.onStop()
        flutterEngine!!.lifecycleChannel.appIsPaused()
    }

    override fun onDestroy() {
        super.onDestroy()
        flutterView!!.detachFromFlutterEngine()
    }

    override fun onDetach() {
        super.onDetach()
        flutterEngine!!.lifecycleChannel.appIsDetached()
    }

}